package nio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
import java.nio.channels.Pipe.SourceChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

import entity.Job;
import entity.Node;
import entity.Task;

public class Controller extends Thread{
	
	public static Selector selector = null;
	public static Pipe pipe=null;
	public static SourceChannel sourceChannel=null;
	
	static{
		 try {
			selector = Selector.open();
			pipe = Pipe.open();
			sourceChannel = pipe.source();
			sourceChannel.configureBlocking(false);
			sourceChannel.register(selector, SelectionKey.OP_READ);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	public static void notice(){
		 try {
			Pipe.SinkChannel sinkChannel = pipe.sink();
			ByteBuffer buf = ByteBuffer.allocate(512);
			buf.clear();
			buf.put("notice".getBytes());
			buf.flip();
			while(buf.hasRemaining()) {
				sinkChannel.write(buf);
			}
		 } catch (IOException e) {
				e.printStackTrace();
		}
		
	}
	
	public void run(){
		
		while (true) {
			try {
				selector.select();
				// 获得selector中选中的项的迭代器，选中的项为注册的事件
				Iterator ite = this.selector.selectedKeys().iterator();
				int count = 0;
				while (ite.hasNext()) {
					count++;
					SelectionKey key = (SelectionKey) ite.next();
					// 删除已选的key,以防重复处理
					ite.remove();
					// 客户端请求连接事件
					if (key.isReadable()) {
						ByteBuffer buf = ByteBuffer.allocate(512);
						Pipe.SourceChannel sourceChannel = (Pipe.SourceChannel) key.channel();
						int bytesRead;
						try {
							bytesRead = sourceChannel.read(buf);
							buf.flip();
							byte[] b = new byte[bytesRead];
							buf.get(b);
							System.out.println("------------------------" + new String(b));
							buf.clear();
						} catch (IOException e) {
							e.printStackTrace();
						}
						execute();
					} 
				}
				System.out.println("count-----------" + count);

			} catch (IOException e) {
				e.printStackTrace();
			}
		
		}
		
	}


	public static void execute(){
		
		while(true){
			int count = 0;
			Iterator<Integer> nodeI = NioRoot.nodeMap.keySet().iterator();
			Node node = null;
			boolean match = false;
			while(nodeI.hasNext()){
				match = false;
				node = NioRoot.nodeMap.get(nodeI.next());
				if(node.getStatus() == 1){
					Iterator<Integer> taskI = NioRoot.taskMap.keySet().iterator();
					Task task = null;
					while(taskI.hasNext()){
						task = NioRoot.taskMap.get(taskI.next());
						if(task.getStatus() == 0){
							Iterator<Integer> jobI = task.getJobs().keySet().iterator();
							Job job = null;
							while(jobI.hasNext()){
								job = task.getJobs().get(jobI.next());
								if(job.getStatus() == 0){
									//分配机器给这个job
									assign(job, node);
									count++;
									match = true;//必须的，否则会分配失败
									break;
								}
							}
							if(match){
								break;
							}
						}
						
					}
					
				}
			}
			System.err.println("Controller：" + count);
			if(count == 0){
				break;
			}
		}
	}
	
	public static void assign(Job job,Node node){
		try {
			node.setStatus(2);
			job.setStatus(1);
			node.setJob(job);
			node.getSc().write(ByteBuffer.wrap(("execute|"+node.getId()+"|"+job.getTask().getId() +"|"+ job.getId() +"\r\n").getBytes()));
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
}
